package com.koron.common.web.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.business.configsettings.utils.ConfigInfoTool;
import com.koron.common.core.business.print.PrintConst;
import com.koron.common.core.business.print.ReportTask;
import com.koron.common.core.business.print.bean.FieldJsonTwo;
import com.koron.common.core.business.print.bean.PrintBusinessBean;
import com.koron.common.core.business.print.bean.PrintTemplateBean;
import com.koron.common.core.business.print.bean.ReportTaskBean;
import com.koron.common.core.business.print.bean.dto.PrintBusinessDto;
import com.koron.common.core.business.print.bean.dto.PrintTemplateDto;
import com.koron.common.core.business.print.printstandard.PrintStandardMapper;
import com.koron.common.core.business.print.printstandard.PrintStandardService;
import com.koron.common.core.business.print.printstandard.ReportServiceStandardImpl;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.FastJsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.text.MessageFormat;
import java.util.*;


@Api(tags = "printServer", description = "中心打印模版管理")
@RestController
@Slf4j
@RequestMapping("/printStandard")
public class PrintStandardController {

//    private static String printHost;    //本地打印控件地址
//    private static String printUrl;        //打印控件回调项目地址


    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }


    @ApiOperation(value = "设计打印模版 （需要先 安装 打印控件） 打开设置器后30分钟后失效，每次保存延长30分钟")
    @GetMapping(value = "/getPrintTemplate.htm")
    public Response<String> getPrintTemplate(@RequestParam("templateId") String templateId) {
        ReportTaskBean taskBean = new ReportTaskBean();
        String key = UUID.randomUUID().toString();
        taskBean.setTimeStamp(new Date().getTime());//记录时间戳
        ReportServiceStandardImpl reportSSI = new ReportServiceStandardImpl();
        PrintTemplateBean printtemplate = new PrintTemplateBean();
        printtemplate.setId(templateId);
        printtemplate.setEamuser(ThreadLocalContext.get());
        reportSSI.setPrintTemplate(printtemplate);
        taskBean.setReportServiceInterface(reportSSI);
        Map<String, String> configmap = ConfigInfoTool.getConfigByCode("common", "print");
        String printUrl = configmap.get("url");
        String printHost = configmap.get("host");
        //返回前端调用地址
        String url = MessageFormat.format(printUrl, PrintConst.TYPE_FORMAT_SET, key, printHost, key);

        ReportTask.printTaskTimedCache.put("Print-" + key, taskBean);//本地缓存一份
        try {
            ReportTask.setPrintData("Print-" + key, new ObjectMapper().writeValueAsString(taskBean));//redis缓存一份
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }

        return Response.ok("获取成功,拿返回地址调起打印设计", url);
    }

    /**
     * 获取打印业务列表
     *
     * @return
     */
    @ApiOperation(value = "获取打印业务列表组")
    @GetMapping("/readPrintBusList.htm")
    public Response<List<PrintBusinessBean>> readPrintBusList() {
        List<PrintBusinessBean> list = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "readPrintBusList", List.class);
        return Response.ok(list);
    }


    /**
     * @param businessCode 打印业务code
     * @return
     */
    @ApiOperation(value = "查询打印业务下面所有的打印模版")
    @GetMapping("/readPrintBusListByBusinessCode.htm")
    public Response<List> readPrintBusListByBusinessCode(String businessCode) {
        List<PrintTemplateBean> list = ADOConnection.runTask(getCurrDs(), factory -> {
            List<PrintTemplateBean> templateListByBusinessCode = factory.getMapper(PrintStandardMapper.class).getTemplateListByBusinessCode(businessCode);
            return templateListByBusinessCode;
        }, List.class);
        return Response.ok(Optional.of(list).orElse(new ArrayList<>()));
    }

    /**
     * 添加打印业务
     *
     * @param eamuser
     * @param dto
     * @return
     */
    @ApiOperation(value = "添加打印业务")
    @PostMapping("/addPrintBus.htm")
    @ResponseBody
    public Response<String> addPrintBus(@ApiIgnore @CasUser EamUser eamuser, @RequestBody PrintBusinessDto dto) {
        PrintBusinessBean bean = new PrintBusinessBean();
        BeanUtils.copyProperties(dto, bean);
        bean.setCreateBy(eamuser.getAccount());
        String id = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "addPrintBus", String.class, bean);
        return Response.ok(id);
    }

    /**
     * 修改打印业务
     *
     * @param eamuser
     * @param dto
     * @return
     */
    @ApiOperation(value = "修改打印业务")
    @PostMapping("/updatePrintBus.htm")
    @ResponseBody
    public Response<Object> updatePrintBus(@ApiIgnore @CasUser EamUser eamuser, @RequestBody PrintBusinessDto dto) {
        PrintBusinessBean bean = new PrintBusinessBean();
        BeanUtils.copyProperties(dto, bean);
        bean.setUpdateBy(eamuser.getAccount());
        bean.setName(StringUtils.trim(bean.getName()));
        if (StringUtils.isBlank(bean.getName())) {
            Assert.isFalse(true, "名称不能为空");
        }
        //验证是否有重复字段
        if (PrintStandardService.verifyRepeat(bean.getField(), "fieldCode")) {
            Assert.isFalse(true, "存在重复字段,添加失败！");
        }
        Response<Object> response = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "updatePrintBus", Response.class, bean);
        return response;
    }

    /**
     * 删除打印业务
     *
     * @param eamuser
     * @param id
     * @return
     */
    @ApiOperation(value = "删除打印业务")
    @DeleteMapping("/deletePrintBus.htm")
    @ResponseBody
    public Response<String> deletePrintBus(@ApiIgnore @CasUser EamUser eamuser, String id) {
        PrintBusinessBean bean = new PrintBusinessBean();
        bean.setId(id);
        bean.setUpdateBy(eamuser.getAccount());
        bean.setDeleteFlag(1);
        Response<String> response = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "updatePrintBus", Response.class, bean);
        return response;
    }

    /**
     * 获取打印模板列表-明细
     *
     * @param businessId 打印业务id
     * @return
     */
    @ApiOperation(value = "获取打印模板列表-明细")
    @GetMapping("/readPrintTemList.htm")
    public Response<List<PrintTemplateBean>> readPrintTemList(String businessId) {
        List<PrintTemplateBean> list = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "readPrintTemList", List.class, businessId);
        return Response.ok(list);
    }

    /**
     * 添加打印模板
     *
     * @param eamuser
     * @param dto
     * @return
     */
    @ApiOperation(value = "添加打印模板")
    @PostMapping("/addPrintTem.htm")
    @ResponseBody
    public Response<String> addPrintTem(@ApiIgnore @CasUser EamUser eamuser, @RequestBody PrintTemplateDto dto) {
        PrintTemplateBean bean = new PrintTemplateBean();
        BeanUtils.copyProperties(dto, bean);
        bean.setCreateBy(eamuser.getAccount());
        String id = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "addPrintTem", String.class, bean);
        return Response.ok(id);
    }

    /**
     * 修改打印模板
     *
     * @param eamuser
     * @param dto
     * @return
     */
    @ApiOperation(value = "修改打印模板")
    @PostMapping("/updatePrintTem.htm")
    public Response<String> updatePrintTem(@ApiIgnore @CasUser EamUser eamuser, @RequestBody PrintTemplateDto dto) {
        PrintTemplateBean bean = new PrintTemplateBean();
        BeanUtils.copyProperties(dto, bean);
        bean.setUpdateBy(eamuser.getAccount());
        bean.setName(StringUtils.trim(bean.getName()));
        Assert.notEmpty(bean.getName(), "模板名称不能为空，修改失败");
        Response<String> response = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "updatePrintTem", Response.class, bean);
        return response;
    }

    /**
     * 设置默认模板
     *
     * @param eamuser
     * @param id
     * @return
     */
    @RequestMapping("/setupDefaultTem.htm")
    @ResponseBody
    public String setupDefaultTem(@ApiIgnore @CasUser EamUser eamuser, String id) {
        PrintTemplateBean bean = new PrintTemplateBean();
        bean.setId(id);
        bean.setUpdateBy(eamuser.getAccount());
        bean.setDefaultFlag(true);
        MessageBean<?> runTask = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "setupDefaultTem", MessageBean.class, bean);
        return runTask.toJson();
    }

    /**
     * 删除打印模板
     *
     * @param eamuser
     * @param id
     * @return
     */
    @ApiOperation("删除打印模板")
    @DeleteMapping("/deletePrintTem.htm")
    @ResponseBody
    public Response<String> deletePrintTem(@ApiIgnore @CasUser EamUser eamuser, String id) {
        PrintTemplateBean bean = new PrintTemplateBean();
        bean.setId(id);
        bean.setUpdateBy(eamuser.getAccount());
        bean.setDeleteFlag(1);

        Response<String> response = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "updatePrintTem", Response.class, bean);
        return response;
    }


    /**
     * 直接打开设计模板
     * 包含
     * 1、新建、更新打印业务
     * 2、新建、返回 模板调用地址
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "直接打开设计模板")
    @PostMapping("/directDesign")
    public Response<String> directDesign(@RequestBody PrintBusinessDto dto) {
        PrintBusinessBean bean = Convert.convert(PrintBusinessBean.class, dto);
        String templateId = ADOConnection.runTask(getCurrDs(), new PrintStandardService(), "directDesign", String.class, bean);
        return getPrintTemplate(templateId);
    }

    @ApiOperation(value = "后端使用生成转义json")
    @PostMapping("/getFieldJsonTwo.htm")
    public Response<String> getFieldJsonTwo(@RequestBody List<FieldJsonTwo> list) {

        String beanToJson = FastJsonUtils.getBeanToJson(list);
        return Response.ok(beanToJson);

    }
}
